package com.kgdev.cweb.mbean.store.order;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import com.kgdev.cweb.beans.prod.impl.OrderDraftBean;
import com.kgdev.cweb.entities.prod.managed.OrderDraft;
import com.kgdev.cweb.mbean.global.session.LoginBean;

@ManagedBean
@ViewScoped
public class OrderDraftList implements Serializable {

	@EJB
	OrderDraftBean orderDraftBean;

	public OrderDraftBean getOrderDraftBean() {
		return orderDraftBean;
	}

	@ManagedProperty(value = "#{loginBean}")
	LoginBean loginBean;

	public void setLoginBean(LoginBean loginBean) {
		this.loginBean = loginBean;
	}

	private List<OrderDraft> orderDrafts;

	public List<OrderDraft> getOrderDrafts() {
		return orderDrafts;
	}

	public void setOrderDrafts(List<OrderDraft> orderDrafts) {
		this.orderDrafts = orderDrafts;
	}

	private static final long serialVersionUID = 1L;

	@PostConstruct
	private void initOrderDrafts() {
		List<OrderDraft> orderDrafts = orderDraftBean.findAll();
		this.orderDrafts = new ArrayList<>();
		for (OrderDraft orderDraft : orderDrafts) {
			if (orderDraft.getClient()
					.equals(loginBean.getAutenticatedClient())) {
				this.orderDrafts.add(orderDraft);
			}
		}
	}

	public String addOrder(Integer orderDraftId) {
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
				.put("orderDraftIdForAdd", orderDraftId);
		return "toOrderAdd";
	}

	public void removeDraft(Integer orderDraftId) {
		orderDraftBean.remove(orderDraftId);
		initOrderDrafts();
	}

}
